<template>
  <div class="app-container">
    <el-card>
      <div class="section-title">基本信息</div>
      <el-form :model="form" label-width="100px" class="detail-form" :disabled="isViewMode">
        <el-form-item label="活动名称" required>
          <el-input v-model="form.activityName" placeholder="活动名称" />
        </el-form-item>
        <el-form-item label="优惠券名称" required>
          <el-input v-model="form.couponName" placeholder="优惠券名称" />
        </el-form-item>
        <el-form-item label="优惠券类型" required>
          <el-select v-model="form.couponType" placeholder="请选择">
            <el-option label="减免现金" value="CASH" />
            <el-option label="打折" value="DISCOUNT" />
          </el-select>
        </el-form-item>
        <el-form-item label="面额" required>
          <el-input v-model="form.amount" />
        </el-form-item>
        <el-form-item label="活动类型" required>
          <el-select v-model="form.activityType">
            <el-option label="免费领取" value="FREE" />
          </el-select>
        </el-form-item>
        <el-form-item label="店铺承担比例" required>
          <el-input v-model="form.shopShareRatio" />
          <template #label>店铺承担比例</template>
        </el-form-item>
        <el-form-item label="发放数量" required>
          <el-input v-model="form.issueCount" />
        </el-form-item>
        <el-form-item label="领取数量限制" required>
          <el-input v-model="form.takeLimit" />
        </el-form-item>
        <el-form-item label="范围描述" required>
          <el-input v-model="form.scopeDesc" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>

      <div class="section-title" style="margin-top: 10px;">使用限制</div>
      <el-form :model="form" label-width="100px" class="detail-form" :disabled="isViewMode">
        <el-form-item label="消费门槛" required>
          <el-input v-model="form.consumeThreshold" />
        </el-form-item>
        <el-form-item label="有效期" required>
          <el-date-picker
            v-model="dateRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DDTHH:mm:ss.SSSZ"
          />
        </el-form-item>
        <el-form-item label="使用范围" required>
          <div class="scope-buttons">
            <el-button :type="form.scopeType==='ALL'?'primary':'default'" @click="form.scopeType='ALL'" :disabled="isViewMode">全品类</el-button>
            <el-button :type="form.scopeType==='PRODUCT'?'primary':'default'" @click="form.scopeType='PRODUCT'" :disabled="isViewMode">指定商品</el-button>
            <el-button :type="form.scopeType==='CATEGORY'?'primary':'default'" @click="form.scopeType='CATEGORY'" :disabled="isViewMode">部分商品分类</el-button>
          </div>
        </el-form-item>
      </el-form>

      <!-- 指定商品选择区域 -->
      <div v-if="form.scopeType === 'PRODUCT'" class="product-selection-section">
        <div class="section-title">指定商品</div>
        <div class="action-buttons">
          <el-button type="primary" @click="openProductDialog" :disabled="isViewMode">选择商品</el-button>
          <el-button @click="batchDeleteProducts" :disabled="isViewMode || selectedProducts.length === 0">批量删除</el-button>
        </div>
        
        <el-table :data="selectedProducts" @selection-change="handleProductSelectionChange" style="margin-top: 15px;">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="商品名称" prop="productName" />
          <el-table-column label="商品价格" prop="price">
            <template #default="scope">
              ¥{{ scope.row.price }}
            </template>
          </el-table-column>
          <el-table-column label="库存" prop="stock" />
          <el-table-column label="操作" width="120" align="center">
            <template #default="scope">
              <el-button link type="danger" @click="deleteProduct(scope.$index)" :disabled="isViewMode">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div style="text-align: left; margin-top: 10px;">
        <el-button @click="goBack">返回</el-button>
        <el-button v-if="!isViewMode" type="primary" @click="handleSave">保存</el-button>
      </div>
    </el-card>

    <!-- 选择商品弹窗 -->
    <el-dialog v-model="productDialogVisible" title="选择商品" width="1000px" append-to-body>
      <div class="search-section">
        <el-form :inline="true" :model="productQueryParams">
          <el-form-item label="商品名称">
            <el-input v-model="productQueryParams.productName" placeholder="请输入商品名称" clearable />
          </el-form-item>
          <el-form-item label="商品分类">
            <el-select v-model="productQueryParams.categoryId" placeholder="请选择商品分类" clearable>
              <el-option 
                v-for="item in categoryOptions" 
                :key="item.id" 
                :label="item.categoryName" 
                :value="item.id" 
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchProducts">搜索</el-button>
          </el-form-item>
        </el-form>
      </div>

      <el-table 
        :data="productList"
        @selection-change="handleProductDialogSelectionChange"
        v-loading="productLoading"
        style="margin-top: 15px;"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="商品信息" min-width="300">
          <template #default="scope">
            <div class="product-info">
              <el-image 
                :src="scope.row.mainImage || '/placeholder.png'" 
                fit="cover"
                style="width: 50px; height: 50px; margin-right: 10px;"
              >
                <template #error>
                  <div class="image-placeholder">
                    <el-icon><Picture /></el-icon>
                  </div>
                </template>
              </el-image>
              <div class="product-details">
                <div class="product-name">{{ scope.row.productName }}</div>
                <div class="product-desc">{{ scope.row.description }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="单位" prop="productUnit" width="80" />
        <el-table-column label="类型" prop="salesModel" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.salesModel === 'wholesale' ? 'primary' : 'info'" size="small">
              {{ scope.row.salesModel === 'wholesale' ? '批发型' : '零售型' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="价格" prop="price" width="120">
          <template #default="scope">
            ¥{{ scope.row.price }}
          </template>
        </el-table-column>
        <el-table-column label="选择" width="80" align="center">
          <template #default="scope">
            <el-icon v-if="isProductSelected(scope.row)" color="#f56c6c"><Check /></el-icon>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="productQueryParams.pageNum"
          v-model:page-size="productQueryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="productTotal"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleProductSizeChange"
          @current-change="handleProductCurrentChange"
        />
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="productDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmProductSelection">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="CouponDetail">
import { getCoupons, addCoupons } from '@/api/coupon/coupons'
import { listPlatform } from '@/api/shangpin/platform'
import { listClassify } from '@/api/shangpin/classify'
import { useRoute, useRouter } from 'vue-router'
import { ref, onMounted, computed, getCurrentInstance, watch } from 'vue'
import { Picture, Check } from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()
const { proxy } = getCurrentInstance()

const form = ref({})
const dateRange = ref([])
const selectedProducts = ref([])
const productDialogVisible = ref(false)
const productList = ref([])
const productTotal = ref(0)
const productLoading = ref(false)
const categoryOptions = ref([])
const dialogSelectedProducts = ref([])

const productQueryParams = ref({
  pageNum: 1,
  pageSize: 10,
  productName: '',
  categoryId: null
})

const isViewMode = computed(() => {
  return route.query.id && route.query.id !== 'new'
})

function goBack(){
  router.back()
}

async function fetchDetail(){
  const id = route.query.id
  if(!id || id === 'new') {
    // 新增模式，初始化表单
    form.value = {
      activityName: '',
      couponName: '',
      couponType: 'CASH',
      amount: '',
      activityType: 'FREE',
      shopShareRatio: '',
      issueCount: '',
      takeLimit: '',
      scopeDesc: '',
      consumeThreshold: '',
      scopeType: 'ALL',
      status: 'CREATED'
    }
    selectedProducts.value = []
    dateRange.value = []
    return
  }
  // 查看模式，获取数据
  const res = await getCoupons(id)
  form.value = res.data || {}
  selectedProducts.value = res.data.couponProductLists || []
  if(form.value.startTime && form.value.endTime){
    dateRange.value = [form.value.startTime, form.value.endTime]
  }
}

async function handleSave(){
  // 表单验证
  if(!form.value.activityName) {
    proxy.$modal.msgError('请输入活动名称')
    return
  }
  if(!form.value.couponName) {
    proxy.$modal.msgError('请输入优惠券名称')
    return
  }
  if(!form.value.amount) {
    proxy.$modal.msgError('请输入面额')
    return
  }
  if(!form.value.shopShareRatio) {
    proxy.$modal.msgError('请输入店铺承担比例')
    return
  }
  if(!form.value.issueCount) {
    proxy.$modal.msgError('请输入发放数量')
    return
  }
  if(!form.value.takeLimit) {
    proxy.$modal.msgError('请输入领取数量限制')
    return
  }
  if(!form.value.scopeDesc) {
    proxy.$modal.msgError('请输入范围描述')
    return
  }
  if(!form.value.consumeThreshold) {
    proxy.$modal.msgError('请输入消费门槛')
    return
  }
  if(!dateRange.value || dateRange.value.length !== 2) {
    proxy.$modal.msgError('请选择有效期')
    return
  }
  if(!form.value.scopeType) {
    proxy.$modal.msgError('请选择使用范围')
    return
  }

  // 设置时间
  form.value.startTime = dateRange.value[0]
  form.value.endTime = dateRange.value[1]
  
  // 设置关联商品
  form.value.couponProductLists = form.value.scopeType === 'PRODUCT'
    ? selectedProducts.value.map(p => ({ 
        productId: p.id, 
        createTime: new Date().toISOString(),
        couponId: form.value.id || null 
      }))
    : []

  try {
    await addCoupons(form.value)
    console.log('form.value',form.value)
    proxy.$modal.msgSuccess('新增成功')
    router.back()
  } catch (error) {
    proxy.$modal.msgError('新增失败')
  }
}

// 商品选择相关方法
function openProductDialog() {
  productDialogVisible.value = true
  loadProducts()
  loadCategories()
}

async function loadProducts() {
  productLoading.value = true
  try {
    const res = await listPlatform(productQueryParams.value)
    productList.value = res.rows || []
    productTotal.value = res.total || 0
  } catch (error) {
    proxy.$modal.msgError('加载商品列表失败')
  } finally {
    productLoading.value = false
  }
}

async function loadCategories() {
  try {
    const res = await listClassify({
      pageNum: 1,
      pageSize: 1000,
      status: 'enabled'
    })
    categoryOptions.value = res.rows || []
  } catch (error) {
    console.error('加载分类失败:', error)
  }
}

function searchProducts() {
  productQueryParams.value.pageNum = 1
  loadProducts()
}

function handleProductSizeChange(val) {
  productQueryParams.value.pageSize = val
  loadProducts()
}

function handleProductCurrentChange(val) {
  productQueryParams.value.pageNum = val
  loadProducts()
}

function handleProductDialogSelectionChange(selection) {
  dialogSelectedProducts.value = selection
}

function isProductSelected(product) {
  return selectedProducts.value.some(p => p.id === product.id)
}

function confirmProductSelection() {
  // 添加新选择的商品到已选列表
  dialogSelectedProducts.value.forEach(product => {
    if (!selectedProducts.value.some(p => p.id === product.id)) {
      selectedProducts.value.push({
        id: product.id,
        productName: product.productName,
        price: product.price,
        stock: product.stock,
        mainImage: product.mainImage,
        productUnit: product.productUnit,
        salesModel: product.salesModel
      })
    }
  })
  productDialogVisible.value = false
  proxy.$modal.msgSuccess('商品选择成功')
}

function handleProductSelectionChange(selection) {
  // 处理已选商品表格的选择变化
}

function deleteProduct(index) {
  selectedProducts.value.splice(index, 1)
}

function batchDeleteProducts() {
  // 批量删除选中的商品
  // 这里需要实现批量删除逻辑
}

onMounted(fetchDetail)

// 监听路由参数变化，重新获取数据
watch(() => route.query.id, () => {
  fetchDetail()
})
</script>

<style scoped>
.section-title{
  font-weight: 600;
  margin-bottom: 12px;
}
.detail-form{
  max-width: 520px;
}
.scope-buttons .el-button{ margin-right: 10px; }

.product-selection-section {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.action-buttons {
  margin-bottom: 15px;
}

.action-buttons .el-button {
  margin-right: 10px;
}

.product-info {
  display: flex;
  align-items: center;
}

.product-details {
  flex: 1;
}

.product-name {
  font-weight: 500;
  margin-bottom: 5px;
}

.product-desc {
  color: #909399;
  font-size: 12px;
}

.image-placeholder {
  width: 50px;
  height: 50px;
  background-color: #f5f7fa;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #c0c4cc;
  font-size: 16px;
}

.search-section {
  margin-bottom: 15px;
}

.pagination-wrapper {
  margin-top: 15px;
  text-align: right;
}
</style>
